import socket,threading,sys
import gnupg,os
from listener import UDPListen

def udpserver(port):
    if(not os.path.exists("./gnupg_server")):
        os.mkdir("./gnupg_server")
    if(not os.path.exists("./gnupg_server/private-keys-v1.d")):
        os.mkdir("./gnupg_server/private-keys-v1.d")
    gpg = gnupg.GPG(gnupghome='./gnupg_server')
    gpg.encoding = 'utf-8'
    if (not len(os.listdir('gnupg_server/private-keys-v1.d'))):
        key=gpg.gen_key(gpg.gen_key_input(key_type="RSA", key_length=1024))
    public_keys = gpg.list_keys()
    keyid=public_keys[0]['keyid']
    ascii_armored_public_key=gpg.export_keys(keyid)

    serverSocket=socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
    serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)#reuse port
    serverSocket.bind(('',int(port)))
    yourName=input('Enter your name:')
    fromName,address=serverSocket.recvfrom(1024)#receive client name
    fromName=fromName.decode()#decode client name
    serverSocket.sendto(yourName.encode(),address)#send server name
    clientkey, address=serverSocket.recvfrom(1024)#receive client pubkey
    clientkey=clientkey.decode()#decode client key
    serverSocket.sendto(ascii_armored_public_key.encode(),address)#send server key
    import_client=gpg.import_keys(clientkey)#import client key

    listener=threading.Thread(target=UDPListen,args=(serverSocket,fromName,gpg,),daemon=True)
    listener.start()
    run=True
    print("Chat started, type /quit or /q to exit")
    while run:
        message=input()
        gpgmsg=str(gpg.encrypt(message,import_client.fingerprints[0],always_trust=True))
        if (message in ["/quit","/q"]):
            run=False
        serverSocket.sendto(gpgmsg.encode(),address)
    serverSocket.close()
    sys.exit(0)
